<template>
  <a-form
    :model="userForm"
    name="userForm"
    :label-col="{ span: 6 }"
    :wrapper-col="{ span: 12 }"
    autocomplete="off"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <a-form-item
      label="新密码"
      name="password"
      :rules="[
        { required: true, message: '请输入密码!' },
        { min: 3, message: '密码长度不能少于3位!' }
      ]"
    >
      <a-input-password v-model:value="userForm.password" />
    </a-form-item>
    
    <a-form-item
      label="确认密码"
      name="confirmPassword"
      :rules="[
        { required: true, message: '请再次输入密码!' },
        { validator: confirmPasswordValidator }
      ]"
    >
      <a-input-password v-model:value="userForm.confirmPassword" />
    </a-form-item>

    <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
      <a-button type="primary" html-type="submit" :loading="submitting.value">提交</a-button>
      <a-button @click="handleReset" style="margin-left: 8px">重置</a-button>
    </a-form-item>
  </a-form>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { updatePassword } from '@/api/system/user';
import { useUserStore } from '@/store/business/user.js'
import { message } from 'ant-design-vue';
import {updatePassword} from '@/api/auth/admin'

const userStore = useUserStore()

const submitting = ref(false);
const userForm = reactive({
  password: '',
  confirmPassword: ''
});

// 自定义验证规则：确认密码必须与密码一致
const confirmPasswordValidator = (_, value) => {
  if (value !== userForm.password) {
    return Promise.reject(new Error('两次输入的密码不一致!'));
  }
  return Promise.resolve();
};

const onFinish = async (record) => {
  submitting.value = true;
  try {
    const data = {
      password: userForm.password,
      confirmPassword: userForm.confirmPassword,
    }
    const response = await updatePassword(data);
    message.success('密码更新成功，请重新登录');
    userStore.logout()
  } catch (error) {
    const errorMessage = error?.response?.data?.msg ?? '密码更新失败';
    message.error(errorMessage);
  }
};

// 表单提交失败的处理函数
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo);
};

// 重置表单
const handleReset = () => {
  userForm.password = '';
  userForm.confirmPassword = '';
};
</script>

<style scoped>
/* 您可以在这里添加一些样式 */
</style>
